<script setup lang="ts">
import { onMounted, reactive, ref, watch } from 'vue';

import { BankOutlined } from '@ant-design/icons-vue';
import { notification } from 'ant-design-vue';

import {
  delDYGoodsInfo,
  get1688ShopStatusList,
  getDYGoodsListFu,
  setGoodsOnLine,
  checkDYGoodsStatusList,
} from '#/api';
import { errimage } from '#/base';
import { useTable } from '#/hooks/useTable';
import { auto1688stor } from '#/store';

const auto1688 = auto1688stor();
const { nowSelectDyShop, bindShopList } = auto1688.auto1688; // bindShopList
const selectShop = ref<any>(nowSelectDyShop?.shopId);
const searchForm = reactive({
  goodsTitle: '',
  offerId: '',
  shopId: selectShop.value,
  shopName: '',
  status: '',
  productId: '',
});
const {
  tableData,
  page,
  loading,
  resetParams,
  getList,
  handleCurrentChange,
  handleSizeChange,
} = useTable({
  apiFn: getDYGoodsListFu,
  params: searchForm,
});
watch(selectShop, () => {
  searchForm.shopId = selectShop.value;
});
const statusOption = ref<any[]>([]);
function getShopStatus() {
  get1688ShopStatusList().then((res) => {
    statusOption.value = res;
    statusOption.value.push({
      name: '全部',
      status: '',
    });
  });
}
onMounted(() => {
  getShopStatus();
});
const columns = [
  {
    title: 'ID',
    dataIndex: 'tbId',
    key: 'tbId',
    width: 70,
    fixed: 'left',
  },
  {
    title: '商品信息',
    dataIndex: 'productInfo',
    key: 'productInfo',
    width: 340,
    fixed: 'left',
  },

  {
    title: '类目',
    dataIndex: 'categoryId1688Names',
    key: 'categoryId1688Names',
    width: 200,
  },

  {
    title: '价格',
    dataIndex: 'referencePrice',
    key: 'referencePrice',
    width: 200,
  },
  {
    title: '复制状态',
    dataIndex: 'publishStatusName',
    key: 'publishStatusName',
    width: 100,
  },
  {
    title: '发布状态',
    dataIndex: 'statusName',
    key: 'statusName',
    width: 260,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    width: 180,
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    width: 200,
    fixed: 'right',
  },
];
function openUrl(offerId: any) {
  window.open(`https://detail.1688.com/offer/${offerId}.html`);
}
function settagcolor(status: any) {
  switch (status) {
    case 0: {
      return 'orange';
    }
    case 1: {
      return 'cyan';
    }
    case 2: {
      return 'red';
    }
    case 3: {
      return 'green';
    }
    case 4: {
      return 'pink';
    }
    default: {
      return 'blue';
    }
  }
}
const showAddBox = ref(false);
const selectProducts = ref<any>([]);
const selectShopId = ref(0);
const selectTbId = ref(0);
function uptonewpeoduct(item: any) {
  selectProducts.value = [item.offerId];
  selectShopId.value = item.shopId;
  selectTbId.value = item.tbId;
  showAddBox.value = true;
}

// 删除商品
const tbId = ref(0);
const showDelGoods = ref(false);
const goodsTitle = ref('');
function showDelGoodsModal(record: any) {
  showDelGoods.value = true;
  goodsTitle.value = record.goodsTitle;
  tbId.value = record.tbId;
}

function delDYGoodsInfoApi() {
  const itemId: number[] = [tbId.value];
  const params = { tbIds: itemId };

  delDYGoodsInfo(params).then((res: any) => {
    showDelGoods.value = false;
    if (res > 0) {
      notification.success({
        message: '商品删除成功',
        description: goodsTitle.value,
      });
      getList();
    }
  });
}


function checkDYGoodsStatusListApi(){
  const params = { shopId: searchForm.shopId };

    checkDYGoodsStatusList(params).then((res: any) => {
    if (res > 0) {      
      getList();
    }
  });
}

function setGoodsOnLineApi(record: any) {
  goodsTitle.value = record.goodsTitle;

  setGoodsOnLine(record.tbId).then((res: any) => {
    if (res === 'success') {
      notification.success({
        message: '商品上架成功',
        description: goodsTitle.value,
      });
      getList();
    } else {
      notification.error({
        message: '商品上架失败',
        description: res,
      });
    }
  });
}
const fieldNames = {
  label: 'shopName',
  value: 'shopId',
};
function openToDoudian(productId: string) {
  open(`https://fxg.jinritemai.com/ffa/g/create?product_id=${productId}`);
}
</script>

<template>
  <div class="relative h-full p-4">
    <div class="mb-4">
      <a-form layout="inline">
        <a-form-item
          class="mb-2"
          label="商品来源店铺"
          style="margin-bottom: 5px"
        >
          <a-select
            v-model:value="selectShop"
            :field-names="fieldNames"
            :options="bindShopList.filter((item: any) => item.pType === 2)"
            style="width: 180px"
          />
        </a-form-item>
        <a-form-item label="商品名称" style="margin-bottom: 5px">
          <a-input
            v-model:value="searchForm.goodsTitle"
            allow-clear
            placeholder="请输入商品名称"
          />
        </a-form-item>
        <a-form-item label="店铺商品ID" style="margin-bottom: 5px">
          <a-input
            v-model:value="searchForm.productId"
            allow-clear
            placeholder="请输入店铺商品ID"
          />
        </a-form-item>
        <a-form-item class="mb-2" label="货源商品ID">
          <a-input
            v-model:value="searchForm.offerId"
            allow-clear
            placeholder="请输入货源商品ID"
          />
        </a-form-item>
        <a-form-item class="mb-2" label="下游店铺名称">
          <a-input
            v-model:value="searchForm.shopName"
            allow-clear
            placeholder="请输入下游店铺名称"
          />
        </a-form-item>
        <!-- <a-form-item class="mb-2" label="下游店铺ID">
          <a-input
            v-model:value="searchForm.shopId"
            allow-clear
            placeholder="请输入下游店铺ID"
          />
        </a-form-item> -->
        <a-form-item class="mb-2" label="铺货状态">
          <a-select
            v-model:value="searchForm.status"
            :field-names="{
              label: 'name',
              value: 'status',
            }"
            :options="statusOption"
            placeholder="铺货状态"
            style="width: 180px"
          />
        </a-form-item>

        <a-form-item>
          <a-button class="mr-2" @click="resetParams">重置</a-button>
          <a-button type="primary" @click="getList">搜索</a-button>
          <a-button type="primary" @click="checkDYGoodsStatusListApi" style="margin-left:10px">检查商品审核状态</a-button>
        </a-form-item>
      </a-form>
    </div>
    <div>
      <a-table
        :columns="columns"
        :data-source="tableData"
        :loading="loading"
        :pagination="{
          total: page.total,
          pageSize: page.pageSize,
          showSizeChanger: true,
          current: page.page,
          class: 'pr-14',
          pageSizeOptions: page.pageSizes,
          showTotal: (total: any, range: any) =>
            `${range[0]}-${range[1]} 总 ${total} 条`,
        }"
        :scroll="{ x: 900 }"
        @change="
          (da: any) => {
            // console.log('change', da, size);
            if (da.pageSize !== page.pageSize) {
              handleSizeChange(da.pageSize);
              return;
            }
            handleCurrentChange(da.current);
          }
        "
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'categoryId1688Names'">
            <a-space direction="vertical">
              <div>货源类目: {{ record.categoryId1688Names }}</div>
              <div>铺货类目: {{ record.categoryIdNames }}</div>
            </a-space>
          </template>
          <template v-if="column.dataIndex === 'referencePrice'">
            <a-space direction="vertical">
              <div>供货价: {{ record.referencePrice }}</div>
              <div>铺货价: {{ record.salePrice }}</div>
            </a-space>
          </template>
          <template v-if="column.dataIndex === 'publishStatusName'">
            <a-tag v-if="record.publishStatusName" color="green">
              {{ record.publishStatusName }}
            </a-tag>
          </template>
          <template v-if="column.dataIndex === 'productInfo'">
            <a-space direction="vertical">
              <a-tag color="orange">
                <BankOutlined /> {{ record.shopName }}
              </a-tag>
              <a-space align="start">
                <a-image
                  :fallback="errimage"
                  :height="60"
                  :src="record.mainPic || 'err'"
                  :width="60"
                  alt=""
                  style="margin-top: 8px; border-radius: 5px"
                />
                <a-space :size="2" direction="vertical">
                  <div class="text-xs">{{ record.goodsTitle }}</div>
                  <div class="text-gray-400" style="font-size: 12px">
                    货源ID：{{ record.offerId }}
                  </div>
                  <a-button
                    size="small"
                    style="font-size: 12px"
                    type="primary"
                    @click="openUrl(record.offerId)"
                  >
                    查看货源详情
                  </a-button>
                </a-space>
              </a-space>
            </a-space>
          </template>

          <template v-if="column.dataIndex === 'statusName'">
            <a-space direction="vertical">
              <a-tag :color="settagcolor(record.status)">
                {{ record.statusName }}
              </a-tag>
              <a-tooltip v-if="record.status !== 3" :title="record.dyMsg">
                <div
                  class="ellipsis-2 text-wrap text-red-500"
                  style="width: 240px; font-size: 12px"
                >
                  {{ record.dyMsg }}
                </div>
              </a-tooltip>
              <div
                v-if="record.status === 3"
                class="text-gray-400"
                style="font-size: 12px"
              >
                商品ID： {{ record.productId }}
              </div>
              <a-button
                v-if="record.productId"
                size="small"
                style="padding: 0"
                type="link"
                @click="openToDoudian(record.productId)"
              >
                前往抖店编辑
              </a-button>
            </a-space>
          </template>
          <template v-if="column.dataIndex === 'action'">
            <a-button
              v-if="
                record.status === 2 ||
                record.status === 10 ||
                record.productId==null
              "
              size="small"
              type="primary"
              @click="uptonewpeoduct(record)"
            >
              重新编辑
            </a-button>

            <a-button
              v-if="
                record.status === 0 ||
                record.status === 2 ||
                record.status === 9 ||
                record.status === 10 
              "
              size="small"
              style="margin-left: 10px"
              type="primary"
              @click="showDelGoodsModal(record)"
            >
              删除
            </a-button>

            <a-button
              v-if="record.status === 5"
              size="small"
              style="margin-left: 10px"
              type="primary"
              @click="setGoodsOnLineApi(record)"
            >
              上架
            </a-button>
          </template>
        </template>
      </a-table>
    </div>
    <set-add-product-box
      v-if="showAddBox"
      v-model="showAddBox"
      :select-item-list="selectProducts"
      :shop-id="selectShopId"
      :tb-id="selectTbId"
    />
    <div>
      <a-modal
        v-model:visible="showDelGoods"
        title="是否确定要删除商品"
        @ok="delDYGoodsInfoApi"
      >
        <p>{{ goodsTitle }}</p>
      </a-modal>
    </div>
  </div>
</template>

<style scoped>
.ellipsis-2 {
  display: -webkit-box;
  overflow: hidden;
  text-overflow: ellipsis;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}
</style>
